package com.lpdemilis.pokermanager;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;

public class NewEventActivity extends Activity implements MyAsyncListener {
	private User user;
	private int groupindex;
	private int groupid;
	private String newEventName;
	protected CustomHttpClient client;
	private EditText eventNameEditText;
	private Spinner eventTimestartDateSpinner;
	private Spinner eventTimestartTimeSpinner;
	private Spinner eventTimeconfirmDateSpinner;
	private Spinner eventTimeconfirmTimeSpinner;
	private EditText eventMaxUsersEditText;
	private EditText eventMinUsersEditText;
	private EditText eventPlaceEditText;
	private EditText eventDescriptionEditText;
	private CheckBox eventReceiveEmailCheckBox;
	private CheckBox eventSendEmailCheckBox;
	private Button cancelButton;
	private Button okButton;
	protected String SERVER_URL;
	private Calendar timestart;
	private Calendar timeconfirm;

	static final int TIMESTART_DATE_DIALOG_ID = 0;
	static final int TIMESTART_TIME_DIALOG_ID = 1;
	static final int TIMECONFIRM_DATE_DIALOG_ID = 2;
	static final int TIMECONFIRM_TIME_DIALOG_ID = 3;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_newevent);

		if (Build.MANUFACTURER.equals("unknown")) {
			SERVER_URL = this.getString(R.string.URL_local);
		} else {
			SERVER_URL = this.getString(R.string.URL);
		}
		
		TextView activityTitleTextView = (TextView) findViewById(R.id.activityTitleTextView);
		Typeface titleTypeface = Typeface.createFromAsset(getAssets(),
                "fonts/POKERPN.TTF");        
        activityTitleTextView.setTypeface(titleTypeface);

		user = (User) getIntent().getSerializableExtra("user");
		groupindex = getIntent().getIntExtra("groupindex", 0);
		groupid = getIntent().getIntExtra("groupid", 0);
		newEventName = getIntent().getStringExtra("newEventName");

		eventNameEditText = (EditText) findViewById(R.id.eventNameEditText);
		eventNameEditText.setText(newEventName);
		eventTimestartDateSpinner = (Spinner) findViewById(R.id.eventTimestartDateSpinner);
		eventTimestartTimeSpinner = (Spinner) findViewById(R.id.eventTimestartTimeSpinner);
		eventTimeconfirmDateSpinner = (Spinner) findViewById(R.id.eventTimeconfirmDateSpinner);
		eventTimeconfirmTimeSpinner = (Spinner) findViewById(R.id.eventTimeconfirmTimeSpinner);
		eventMaxUsersEditText = (EditText) findViewById(R.id.eventMaxUsersEditText);
		eventMinUsersEditText = (EditText) findViewById(R.id.eventMinUsersEditText);
		eventPlaceEditText = (EditText) findViewById(R.id.eventPlaceEditText);
		eventDescriptionEditText = (EditText) findViewById(R.id.eventDescriptionEditText);
		eventReceiveEmailCheckBox = (CheckBox) findViewById(R.id.eventReceiveEmailCheckBox);
		eventSendEmailCheckBox = (CheckBox) findViewById(R.id.eventSendEmailCheckBox);
		cancelButton = (Button) findViewById(R.id.cancelButton);
		okButton = (Button) findViewById(R.id.okButton);

		cancelButton.setOnClickListener(cancelButtonClickListener);
		okButton.setOnClickListener(okButtonClickListener);

		timestart = Calendar.getInstance();
		timestart.set(Calendar.DAY_OF_YEAR, timestart.get(Calendar.DAY_OF_YEAR) + 2);
		timeconfirm = Calendar.getInstance();
		timeconfirm.set(Calendar.DAY_OF_YEAR, timeconfirm.get(Calendar.DAY_OF_YEAR) + 1);

		eventTimestartDateSpinner
				.setOnTouchListener(eventTimestartDateSpinnerOnTouchListener);
		eventTimestartTimeSpinner
				.setOnTouchListener(eventTimestartTimeSpinnerOnTouchListener);
		eventTimeconfirmDateSpinner
				.setOnTouchListener(eventTimeconfirmDateSpinnerOnTouchListener);
		eventTimeconfirmTimeSpinner
				.setOnTouchListener(eventTimeconfirmTimeSpinnerOnTouchListener);

		updateDisplay();
	}

	public enum ActionsEnum {
		createEvent, error;
	}

	@Override
	public void executeReturn(String returnValue) {
		String[] returnArray;
		returnArray = returnValue.split("##");

		ActionsEnum action;

		try {
			action = ActionsEnum.valueOf(returnArray[0]);
		} catch (Exception e) {
			action = ActionsEnum.error;
		}

		switch (action) {
		case createEvent:
			createEventReturn(returnArray);
			break;
		case error:
			errorReturn(returnArray);
			break;
		}
	}

	private void errorReturn(String[] returnArray) {

	}

	private void createEventReturn(String[] returnArray) {
		if (returnArray.length <= 1) {
			errorReturn(returnArray);
		} else {
			Intent intent = new Intent(NewEventActivity.this,
					EventActivity.class);
			intent.putExtra("eventid", Integer.parseInt(returnArray[1]));
			intent.putExtra("user", user);
			intent.putExtra("groupindex", groupindex);
			NewEventActivity.this.startActivity(intent);
			NewEventActivity.this.finish();
		}
	}

	@Override
	public void onBackPressed() {
		cancelCreation();
	}

	public void cancelCreation() {
		Intent intent = new Intent(NewEventActivity.this, MainActivity.class);
		intent.putExtra("groupindex", groupindex);
		intent.putExtra("user", user);
		NewEventActivity.this.startActivity(intent);
		NewEventActivity.this.finish();
	}

	View.OnClickListener okButtonClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					NewEventActivity.this).create();
			alertDialog.setTitle(R.string.error);

			if (eventNameEditText.getText().toString().trim().equals("")) {
				alertDialog.setMessage(NewEventActivity.this
						.getString(R.string.name_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								eventNameEditText.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			if (timestart.before(Calendar.getInstance())) {
				alertDialog.setMessage(NewEventActivity.this
						.getString(R.string.timestart_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								eventTimestartDateSpinner.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			if ((timeconfirm.before(Calendar.getInstance()))
					|| (timeconfirm.after(timestart))) {
				alertDialog.setMessage(NewEventActivity.this
						.getString(R.string.timeconfirm_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								eventTimeconfirmDateSpinner.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			if ((eventMaxUsersEditText.getText().toString().trim().equals(""))
					|| (Integer.parseInt(eventMaxUsersEditText.getText()
							.toString()) < 2)) {
				alertDialog.setMessage(NewEventActivity.this
						.getString(R.string.maxusers_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								eventMaxUsersEditText.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			if ((eventMinUsersEditText.getText().toString().trim().equals(""))
					|| (Integer.parseInt(eventMinUsersEditText.getText()
							.toString()) < 2)) {
				alertDialog.setMessage(NewEventActivity.this
						.getString(R.string.minusers_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								eventMinUsersEditText.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			if (eventPlaceEditText.getText().toString().trim().equals("")) {
				alertDialog.setMessage(NewEventActivity.this
						.getString(R.string.place_error));
				alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								eventPlaceEditText.requestFocus();
							}
						});

				alertDialog.show();
				return;
			}

			createEvent();
		}
	};

	View.OnClickListener cancelButtonClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			cancelCreation();
		}
	};

	public void createEvent() {
		try {
			client = new CustomHttpClient(this, this.getString(R.string.wait_message), true);
			String action = ActionsEnum.createEvent.toString();
			String paramName1 = "eventname";
			String paramValue1 = eventNameEditText.getText().toString();
			String paramName2 = "eventtimestart";
			Timestamp timestartTimestamp = new Timestamp(timestart.getTimeInMillis());
			String paramValue2 = String.valueOf(timestartTimestamp.getTime()).subSequence(0, 10).toString();			 
			String paramName3 = "eventtimeconfirm";
			Timestamp timeconfirmTimestamp = new Timestamp(timeconfirm.getTimeInMillis());
			String paramValue3 = String.valueOf(timeconfirmTimestamp.getTime()).subSequence(0, 10).toString();
			String paramName4 = "eventmaxusers";
			String paramValue4 = eventMaxUsersEditText.getText().toString();
			String paramName5 = "eventminusers";
			String paramValue5 = eventMinUsersEditText.getText().toString();
			String paramName6 = "eventplace";
			String paramValue6 = eventPlaceEditText.getText().toString();
			String paramName7 = "eventdescription";
			String paramValue7 = eventDescriptionEditText.getText().toString();
			String paramName8 = "eventreceiveemail";
			String paramValue8 = String.valueOf(eventReceiveEmailCheckBox
					.isChecked());
			String paramName9 = "eventsendemail";
			String paramValue9 = String.valueOf(eventSendEmailCheckBox
					.isChecked());
			String paramName10 = "groupid";
			String paramValue10 = String.valueOf(groupid);
			String paramName11 = "userid";
			String paramValue11 = String.valueOf(user.getId());
			client.execute(SERVER_URL, action, paramName1, paramValue1,
					paramName2, paramValue2, paramName3, paramValue3,
					paramName4, paramValue4, paramName5, paramValue5,
					paramName6, paramValue6, paramName7, paramValue7,
					paramName8, paramValue8, paramName9, paramValue9,
					paramName10, paramValue10, paramName11, paramValue11);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// updates the date in the TextView
	private void updateDisplay() {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy",
				Locale.getDefault());
		SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("HH:mm",
				Locale.getDefault());

		String[] eventTimestartDateStrings = new String[1];
		eventTimestartDateStrings[0] = simpleDateFormat.format(timestart
				.getTime());
		ArrayAdapter<String> eventTimestartDateSpinnerArrayAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_dropdown_item,
				eventTimestartDateStrings);
		eventTimestartDateSpinnerArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_item);
		eventTimestartDateSpinner
				.setAdapter(eventTimestartDateSpinnerArrayAdapter);

		String[] eventTimestartTimeStrings = new String[1];
		eventTimestartTimeStrings[0] = simpleTimeFormat.format(timestart
				.getTime());
		ArrayAdapter<String> eventTimestartTimeSpinnerArrayAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_dropdown_item,
				eventTimestartTimeStrings);
		eventTimestartTimeSpinnerArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_item);
		eventTimestartTimeSpinner
				.setAdapter(eventTimestartTimeSpinnerArrayAdapter);

		String[] eventTimeconfirmDateStrings = new String[1];
		eventTimeconfirmDateStrings[0] = simpleDateFormat.format(timeconfirm
				.getTime());
		ArrayAdapter<String> eventTimeconfirmDateSpinnerArrayAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_dropdown_item,
				eventTimeconfirmDateStrings);
		eventTimeconfirmDateSpinnerArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_item);
		eventTimeconfirmDateSpinner
				.setAdapter(eventTimeconfirmDateSpinnerArrayAdapter);

		String[] eventTimeconfirmTimeStrings = new String[1];
		eventTimeconfirmTimeStrings[0] = simpleTimeFormat.format(timeconfirm
				.getTime());
		ArrayAdapter<String> eventTimeconfirmTimeSpinnerArrayAdapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_dropdown_item,
				eventTimeconfirmTimeStrings);
		eventTimeconfirmTimeSpinnerArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_item);
		eventTimeconfirmTimeSpinner
				.setAdapter(eventTimeconfirmTimeSpinnerArrayAdapter);
	}

	private DatePickerDialog.OnDateSetListener timestartDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			timestart.set(Calendar.YEAR, year);
			timestart.set(Calendar.MONTH, monthOfYear);
			timestart.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			updateDisplay();
		}
	};

	private TimePickerDialog.OnTimeSetListener timestartTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			timestart.set(Calendar.HOUR_OF_DAY, hourOfDay);
			timestart.set(Calendar.MINUTE, minute);
			updateDisplay();
		}
	};

	private DatePickerDialog.OnDateSetListener timeconfirmDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			timeconfirm.set(Calendar.YEAR, year);
			timeconfirm.set(Calendar.MONTH, monthOfYear);
			timeconfirm.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			updateDisplay();
		}
	};

	private TimePickerDialog.OnTimeSetListener timeconfirmTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			timeconfirm.set(Calendar.HOUR_OF_DAY, hourOfDay);
			timeconfirm.set(Calendar.MINUTE, minute);
			updateDisplay();
		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIMECONFIRM_DATE_DIALOG_ID:
			return new DatePickerDialog(this, timeconfirmDateSetListener,
					timeconfirm.get(Calendar.YEAR),
					timeconfirm.get(Calendar.MONTH),
					timeconfirm.get(Calendar.DAY_OF_MONTH));
		case TIMECONFIRM_TIME_DIALOG_ID:
			return new TimePickerDialog(this, timeconfirmTimeSetListener,
					timeconfirm.get(Calendar.HOUR_OF_DAY),
					timeconfirm.get(Calendar.MINUTE),
					DateFormat.is24HourFormat(this));
		case TIMESTART_DATE_DIALOG_ID:
			return new DatePickerDialog(this, timestartDateSetListener,
					timestart.get(Calendar.YEAR),
					timestart.get(Calendar.MONTH),
					timestart.get(Calendar.DAY_OF_MONTH));
		case TIMESTART_TIME_DIALOG_ID:
			return new TimePickerDialog(this, timestartTimeSetListener,
					timestart.get(Calendar.HOUR_OF_DAY),
					timestart.get(Calendar.MINUTE),
					DateFormat.is24HourFormat(this));
		}
		return null;
	}

	private View.OnTouchListener eventTimestartDateSpinnerOnTouchListener = new View.OnTouchListener() {
		@SuppressWarnings("deprecation")
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_UP) {
				showDialog(TIMESTART_DATE_DIALOG_ID);
			}
			return true;
		}
	};

	private View.OnTouchListener eventTimestartTimeSpinnerOnTouchListener = new View.OnTouchListener() {
		@SuppressWarnings("deprecation")
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_UP) {
				showDialog(TIMESTART_TIME_DIALOG_ID);
			}
			return true;
		}
	};

	private View.OnTouchListener eventTimeconfirmDateSpinnerOnTouchListener = new View.OnTouchListener() {
		@SuppressWarnings("deprecation")
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_UP) {
				showDialog(TIMECONFIRM_DATE_DIALOG_ID);
			}
			return true;
		}
	};

	private View.OnTouchListener eventTimeconfirmTimeSpinnerOnTouchListener = new View.OnTouchListener() {
		@SuppressWarnings("deprecation")
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_UP) {
				showDialog(TIMECONFIRM_TIME_DIALOG_ID);
			}
			return true;
		}
	};
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_newevent, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_logoff:
			Intent intent = new Intent(NewEventActivity.this, LoginActivity.class);
			NewEventActivity.this.startActivity(intent);
			NewEventActivity.this.finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}